//
//  PromptChatVCViewController.m
//  SIPphone
//
//  Created by wrt on 13-12-3.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "PromptChatVCViewController.h"
#import "PromptChatDateBase.h"
#import "IncomingMessage.h"
#import "CallViewController.h"
#import "SIPInterface.h"

@interface PromptChatVCViewController () <JSMessagesViewDelegate,JSMessagesViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) NSMutableArray *messageArray;
@property (strong, nonatomic) UIImage *willSendImage;
@property (strong, nonatomic) NSMutableArray *timestamps;

@property (strong, nonatomic) NSMutableArray *timeStr;
@property (strong, nonatomic) NSMutableArray *contentMsg;
@property (strong, nonatomic) NSMutableArray *isTextOrImg;
@property (strong, nonatomic) NSMutableArray *isComeOrOut;
@property (strong, nonatomic) NSMutableArray *isSuccess;
@property (strong, nonatomic) NSMutableArray *isSuccessReal;

@property (strong, nonatomic) NSMutableArray *onlyDataNumber;

@property (strong, nonatomic) NSMutableArray *whoArray;
@property (strong, nonatomic) NSString *tempUserName;
@property (strong, nonatomic) NSString *tempIpport;
@property (strong, nonatomic) NSString *tempMarkName;
@property (assign, nonatomic) int begin;
@property (assign, nonatomic) int lastCount;
@property (assign, nonatomic) float lastHeight;

@end

@implementation PromptChatVCViewController

@synthesize messageArray = _messageArray, willSendImage = _willSendImage, timestamps = _timestamps, whoArray = _whoArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//带用户名的初始化方法
- (id)initWithUserName:(NSString *)userName andIpport:(NSString *)ipport andMarkName:(NSString *)markName
{
    self = [super init];
    if (self)
    {
        self.tempUserName = [[NSString alloc] init];
        self.tempUserName = userName;
        self.tempIpport = [[NSString alloc] init];
        self.tempIpport = ipport;
        self.tempMarkName = [[NSString alloc] init];
        self.tempMarkName = markName;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:YES forKey:@"ISINPROMPTCHATVIEW"];
    [defaults synchronize];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:NO forKey:@"ISINPROMPTCHATVIEW"];
    [defaults synchronize];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.delegate = self;
    self.dataSource = self;
    self.title = self.tempMarkName;
    self.begin = 0;
    
    if (_refreshTableView == nil)
    {
        //初始化下拉刷新控件
        EGORefreshTableHeaderView *refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
        refreshView.delegate = self;
        //将下拉刷新控件作为子控件添加到UItableView中
        [self.tableView addSubview:refreshView];
        _refreshTableView = refreshView;
    }
    
    //新来消息的通知
//    IncomingMessage *newMessage = [[IncomingMessage alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageIncoming:) name:@"HAVENEWFRIENDCHATMESSAGE" object:nil];
    //得到回来的信息状态的通知 成功或者失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgReturnIsSuccess:) name:@"MESSAGERETURNISSUCCESS" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgReturnIsFalse:) name:@"MESSAGERETURNISFALSE" object:nil];
    
    //点了删除之后的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deletePromptChat) name:@"DELETEPROMPTCHATDATA" object:nil];
    
    //来电的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingCallWithChatRoom) name:@"ISINCOMINGWITHCHATROOM" object:nil];
    
    self.messageArray = [[NSMutableArray alloc] init];
    self.timestamps = [[NSMutableArray alloc] init];
    self.whoArray = [[NSMutableArray alloc] init];
    self.isTextOrImg = [[NSMutableArray alloc] init];
    self.timeStr = [[NSMutableArray alloc] init];
    self.isComeOrOut = [[NSMutableArray alloc] init];
    self.contentMsg = [[NSMutableArray alloc] init];
    self.isSuccess = [[NSMutableArray alloc] init];
    self.isSuccessReal = [[NSMutableArray alloc] init];
    self.onlyDataNumber = [[NSMutableArray alloc] init];
    
    PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
    [promptDB readDBForpart:self.tempUserName andIpport:self.tempIpport andBeginNumber:self.begin];
    
    [self.contentMsg addObjectsFromArray:promptDB.partContentArray];
    [self.isTextOrImg addObjectsFromArray:promptDB.partIsTextOrImgArray];
    [self.isComeOrOut addObjectsFromArray:promptDB.partIsOutOrCome];
    [self.timeStr addObjectsFromArray:promptDB.partTimeArray];
    [self.isSuccess addObjectsFromArray:promptDB.partIsSucceedArray];
    
    for (int i = 0; i < self.isTextOrImg.count; i++)
    {
        if ([self.isTextOrImg[i] isEqualToString:@"Text"])
        {
            [self.messageArray addObject:[NSDictionary dictionaryWithObject:self.contentMsg[i] forKey:@"Text"]];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *date = [dateFormatter dateFromString:self.timeStr[i]];
            [self.timestamps addObject:date];
            [self.whoArray addObject:self.isComeOrOut[i]];
            [self.isSuccessReal addObject:self.isSuccess[i]];
            [self.onlyDataNumber addObject:[NSNumber numberWithInt:0]];
        }
        else
        {
//                [self.messageArray addObject:[NSDictionary dictionaryWithObject:promptDB.contentArray[i] forKey:@"Image"]];
//                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//                NSDate *date = [dateFormatter dateFromString:promptDB.timeArray[i]];
//                [self.timestamps addObject:date];
//                [self.whoArray addObject:promptDB.isOutOrCome[i]];
        }
    }
}

- (void)incomingCallWithChatRoom
{
    dispatch_async(dispatch_get_main_queue(),^{
        //切换到来电视频界面
        CallViewController *callVC = [[CallViewController alloc] initWithIncomingType:2];
        callVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentModalViewController:callVC animated:YES];
    });
}

- (void)deletePromptChat
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"confirm delete all chat messages with that contact?", @"确认删除与该联系人的所有聊天消息吗? Confirm delete all chat messages with that contact?") delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"取消 cancel") otherButtonTitles:NSLocalizedString(@"delete", @"删除 Delete"), nil];
    [alert show];
}

- (void)newMessageIncoming:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(),^{
        IncomingMessage *newMessage = [[IncomingMessage alloc] init];
        newMessage = (IncomingMessage *)notification.object;
        if ([newMessage.textOrImage isEqualToString:@"Text"])
        {
            if (newMessage.messageContent == nil)
            {
                newMessage.messageContent = [NSString stringWithFormat:@"❗%@",NSLocalizedString(@"error Message", @"错误信息 Error Message")];
            }
            [self.messageArray addObject:[NSDictionary dictionaryWithObject:newMessage.messageContent forKey:@"Text"]];
            if (newMessage.date == nil)
            {
                NSDate *date = [NSDate date];
                [self.timestamps addObject:date];
            }
            else
            {
                [self.timestamps addObject:newMessage.date];
            }
            
            [self.whoArray addObject:@"come"];
            [self.isSuccessReal addObject:@"成功"];
            [self.onlyDataNumber addObject:[NSNumber numberWithInt:0]];
            [JSMessageSoundEffect playMessageReceivedSound];
            [self finishCome];
        }
        else
        {
            
        }
        self.begin = self.begin + 1;
    });
}

- (void)msgReturnIsSuccess:(NSNotification *)notification
{
    IncomingMessage *newMessage = [[IncomingMessage alloc] init];
    newMessage = (IncomingMessage *)notification.object;
    BOOL isChang = NO;
    for (int i = 0; i < self.isSuccessReal.count; i++)
    {
        NSNumber *onlyForData = self.onlyDataNumber[i];
        if (newMessage.userdata != 0 && newMessage.userdata == [onlyForData intValue])
        {
            [self.isSuccessReal replaceObjectAtIndex:i withObject:@"成功"];
            isChang = YES;
            break;
        }
    }
    if (isChang == YES)
    {
        dispatch_async(dispatch_get_main_queue(),^{
            [self.tableView reloadData];
        });
    }
    self.begin = self.begin + 1;
}

- (void)msgReturnIsFalse:(NSNotification *)notification
{
    IncomingMessage *newMessage = [[IncomingMessage alloc] init];
    newMessage = (IncomingMessage *)notification.object;
    BOOL isChang = NO;
    for (int i = 0; i < self.isSuccessReal.count; i++)
    {
        NSNumber *onlyForData = self.onlyDataNumber[i];
        if (newMessage.userdata != 0 && newMessage.userdata == [onlyForData intValue])
        {
            [self.isSuccessReal replaceObjectAtIndex:i withObject:@"失败"];
            isChang = YES;
            break;
        }
    }
    if (isChang == YES)
    {
        dispatch_async(dispatch_get_main_queue(),^{
            [self.tableView reloadData];
        });
    }
    self.begin = self.begin + 1;
}

#pragma mark - 
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageArray.count;
}

#pragma mark - 
#pragma mark Message View Delegate  
//发送消息的按钮
- (void)sendPressed:(UIButton *)sender withText:(NSString *)text
{
    NSDate *nowTime = [NSDate date];
    [self.messageArray addObject:[NSDictionary dictionaryWithObject:text forKey:@"Text"]];
    [self.whoArray addObject:@"out"];
    [self.timestamps addObject:nowTime];
    [self.isSuccessReal addObject:@"loading"];
    [self.onlyDataNumber addObject:[NSNumber numberWithInt:(int)nowTime]];
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface sendMessageWithUrl:nil andOnedata:(int)nowTime andTextContent:text];
    
    [JSMessageSoundEffect playMessageSentSound];
    
    [self finishSend];
}

- (void)cameraPressed:(id)sender
{
    //相机按钮的处理方法，暂时不用传递相片
}

//信息弹出的形式，是显示接收消息还是发出消息
- (JSBubbleMessageType)messageTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.whoArray[indexPath.row] isEqualToString:@"out"])
    {
        return JSBubbleMessageTypeOutgoing;
    }
    else
    {
        return JSBubbleMessageTypeIncoming;
    }
}

//弹出窗口的样式 3种
- (JSBubbleMessageStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return JSBubbleMessageStyleFlat;
}

//信息媒体的类型 文字或者图片
- (JSBubbleMediaType)messageMediaTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Text"])
    {
        return JSBubbleMediaTypeText;
    }
    else if([[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Image"])
    {
        return JSBubbleMediaTypeImage;
    }
    return -1;
}

//是否成功发送或者失败或者是正在发送中
- (int)messageStatusForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.isSuccessReal[indexPath.row] isEqualToString:@"成功"])
    {
        return 1;
    }
    else if ([self.isSuccessReal[indexPath.row] isEqualToString:@"失败"])
    {
        return 0;
    }
    else
    {
        return 2;
    }
}

//发送按钮
- (UIButton *)sendButton
{
    return [UIButton defaultSendButton];
}

//时间显示
- (JSMessagesViewTimestampPolicy)timestampPolicy
{
    //设置时间的显示 可以给予条件然后再显示时间 JSMessagesViewTimestampPolicyCustom
    return JSMessagesViewTimestampPolicyCustom;
}

//头像是否两边显示
- (JSMessagesViewAvatarPolicy)avatarPolicy
{
    return JSMessagesViewAvatarPolicyBoth;
}

//头像的显示样式
- (JSAvatarStyle)avatarStyle
{
    return JSAvatarStyleSquare;
}

//输入栏的样式
- (JSInputBarStyle)inputBarStyle
{
    return JSInputBarStyleFlat;
}

//  可选的方法，如果你需要使用JSMessagesViewTimestampPolicyCustom 来判断显示时间的条件
- (BOOL)hasTimestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDate *date1 = self.timestamps[indexPath.row];
    if (indexPath.row == 0)
    {
        return YES;
    }
    else
    {
        NSDate *date2 = self.timestamps[indexPath.row - 1];
        NSTimeInterval betweenDates= [date1 timeIntervalSinceDate:date2];
        double between = fabs(betweenDates);
        if (between > 300.0)
        {
            return YES;
        }
        return NO;
    }
}

#pragma mark -
#pragma mark Message View data soure
//文字
- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Text"])
    {
        return [[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Text"];
    }
    return nil;
}

//时间
- (NSDate *)timestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.timestamps objectAtIndex:indexPath.row];
}

//对方的头像
- (UIImage *)avatarImageForIncomingMessage
{
    return [UIImage imageNamed:@"app_panel_friendcard_icon.png"];
}

//自己的头像
- (UIImage *)avatarImageForOutgoingMessage
{
    return [UIImage imageNamed:@"app_panel_friendcard_icon.png"];
}

//图片的数据
- (id)dataForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Image"])
    {
        return [[self.messageArray objectAtIndex:indexPath.row] objectForKey:@"Image"];
    }
    return nil;
}

#pragma UIImagePicker Delegate
#pragma mark -
#pragma mark Image picker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //选择照片
    NSLog(@"Chose image!  Details:  %@", info);
    
    self.willSendImage = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.messageArray addObject:[NSDictionary dictionaryWithObject:self.willSendImage forKey:@"Image"]];
    [self.timestamps addObject:[NSDate date]];
    [self.tableView reloadData];
    [self scrollToBottomAnimated:YES];
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //取消选择图片后的操作
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 
#pragma mark alertViewDelegateMethod
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        
    }
    if (buttonIndex == 1)
    {
        PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
        
        [promptDB deleteChatDBWithUserName:self.tempUserName andIpport:self.tempIpport];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"deleted successfully", @"删除成功 Deleted successfully") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [self performSelector:@selector(returnViewController) withObject:self afterDelay:0.5];
        
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }
}

- (void)returnViewController
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark EGOrefreshMethod
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    //竖向转动
    return NO;
}

- (void)reloadTableViewDataSource
{
    //开始加载时调用的方法
    _reloading = YES;
    //开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞
    [NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil];
//    [self performSelectorOnMainThread:@selector(doInBackground) withObject:nil waitUntilDone:YES];
}

//这个方法运行于子线程中，完成获取刷新数据的操作
-(void)doInBackground
{

    
    PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
    self.begin = self.begin + 15;
    [promptDB readDBForpart:self.tempUserName andIpport:self.tempIpport andBeginNumber:self.begin];
    
    [self.contentMsg removeAllObjects];
    [self.isTextOrImg removeAllObjects];
    [self.isComeOrOut removeAllObjects];
    [self.timeStr removeAllObjects];
    [self.isSuccess removeAllObjects];
    
    [self.contentMsg addObjectsFromArray:promptDB.partContentArray];
    [self.isTextOrImg addObjectsFromArray:promptDB.partIsTextOrImgArray];
    [self.isComeOrOut addObjectsFromArray:promptDB.partIsOutOrCome];
    [self.timeStr addObjectsFromArray:promptDB.partTimeArray];
    [self.isSuccess addObjectsFromArray:promptDB.partIsSucceedArray];

    
    for (int i = 0; i < self.isTextOrImg.count; i++)
    {
        if ([self.isTextOrImg[i] isEqualToString:@"Text"])
        {
            [self.messageArray insertObject:[NSDictionary dictionaryWithObject:self.contentMsg[i] forKey:@"Text"] atIndex:i];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *date = [dateFormatter dateFromString:self.timeStr[i]];
            [self.timestamps insertObject:date atIndex:i];
            [self.whoArray insertObject:self.isComeOrOut[i] atIndex:i];
            [self.isSuccessReal insertObject:self.isSuccess[i] atIndex:i];
            [self.onlyDataNumber insertObject:[NSNumber numberWithInt:0] atIndex:i];
        }
        else
        {
            //                [self.messageArray addObject:[NSDictionary dictionaryWithObject:promptDB.contentArray[i] forKey:@"Image"]];
            //                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            //                NSDate *date = [dateFormatter dateFromString:promptDB.timeArray[i]];
            //                [self.timestamps addObject:date];
            //                [self.whoArray addObject:promptDB.isOutOrCome[i]];
        }
    }
    
    [NSThread sleepForTimeInterval:0.5];
	//后台操作线程执行完后，到主线程更新UI
	[self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
    //完成加载时调用的方法
    
	_reloading = NO;
	[_refreshTableView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
	[self.tableView reloadData];
    [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - 374 - self.lastHeight) animated:NO];
    if (self.messageArray.count % 15 != 0 || self.messageArray.count == self.lastCount)
    {
        [_refreshTableView changeStatusLabelText];
        _refreshTableView = nil;
    }

    
    self.lastCount = self.messageArray.count;
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[_refreshTableView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshTableView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	[self reloadTableViewDataSource];
//	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
    //返回当前状态是无刷新还是刷新状态
	return _reloading; // should return if data source model is reloading
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    NSLog(@"%f",self.tableView.contentSize.height - 374);
//    
//    NSLog(@"%f,%f",scrollView.contentOffset.x,scrollView.contentOffset.y);
    
    self.lastHeight = scrollView.contentSize.height - 374 - scrollView.contentOffset.y - 60;
    NSLog(@"%f",self.lastHeight);
}





//dealloc中取消监听
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"HAVENEWFRIENDCHATMESSAGE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DELETEPROMPTCHATDATA" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MESSAGERETURNISSUCCESS" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MESSAGERETURNISFALSE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ISINCOMINGWITHCHATROOM" object:nil];
}

@end
